from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.utils import timezone
from django.db.models import Q, Count, Sum, Avg
from django.db.models.functions import TruncDate
from .models import WallPost, WallComment, PostLike, User
from .serializers import WallPostSerializer, WallCommentSerializer
from datetime import timedelta, datetime
import json
from rest_framework.parsers import MultiPartParser, FormParser,JSONParser
from rest_framework.decorators import action
from django.db import IntegrityError
from rest_framework import viewsets
import os
from django.conf import settings
from django.http import JsonResponse

class WallPostViewSet(viewsets.ModelViewSet):
    """学习墙帖子视图集"""
    queryset = WallPost.objects.all()
    serializer_class = WallPostSerializer
    permission_classes = []
    parser_classes = (MultiPartParser, FormParser,JSONParser)

    def get_queryset(self):
        queryset = WallPost.objects.all()
        tag = self.request.query_params.get('tag')
        time_range = self.request.query_params.get('range')
        search = self.request.query_params.get('search')
        
        # 搜索过滤
        if search:
            queryset = queryset.filter(content__icontains=search)
        
        # 标签过滤
        if tag:
            queryset = queryset.filter(tags__contains=tag)
        
        # 时间范围过滤
        if time_range:
            now = timezone.now()
            if time_range == 'week':
                start_time = now - timedelta(days=7)
                queryset = queryset.filter(created_at__gte=start_time)
            elif time_range == 'month':
                start_time = now - timedelta(days=30)
                queryset = queryset.filter(created_at__gte=start_time)
        
        return queryset.order_by('-created_at')

    def perform_create(self, serializer):
        data = self.request.data.copy()
        tags = data.get('tags', [])
        # 如果 tags 已经是列表就直接使用，否则尝试解析 JSON
        if isinstance(tags, str):
            try:
                tags = json.loads(tags)
            except json.JSONDecodeError:
                tags = []
        
        try:
            # 打印接收到的数据
            print("接收到的数据:", data)
            print("处理后的 tags:", tags)
            
            # 处理图片上传
            if 'image' in self.request.FILES:
                image = self.request.FILES['image']
                # 确保上传目录存在
                upload_dir = os.path.join(settings.MEDIA_ROOT, 'wall_images')
                if not os.path.exists(upload_dir):
                    os.makedirs(upload_dir)
                
                # 生成文件路径
                filename = f"{data.get('user')}_{timezone.now().strftime('%Y%m%d%H%M%S')}_{image.name}"
                filepath = os.path.join(upload_dir, filename)
                
                # 保存文件
                with open(filepath, 'wb+') as destination:
                    for chunk in image.chunks():
                        destination.write(chunk)
                
                # 保存相对路径到数据库
                relative_path = f'wall_images/{filename}'
                serializer.save(
                    user_id=int(data.get('user')),  # 确保是整数
                    tags=tags,
                    image=relative_path,
                    likes_count=0,
                    comments_count=0
                )
            else:
                serializer.save(
                    user_id=int(data.get('user')),  # 确保是整数
                    tags=tags,
                    likes_count=0,
                    comments_count=0
                )
        except Exception as e:
            print("创建帖子时出错:", str(e))
            raise

    def get_serializer_context(self):
        """添加 request 到序列化器上下文"""
        context = super().get_serializer_context()
        context['request'] = self.request
        return context

    @action(detail=True, methods=['post'])
    def like(self, request, pk=None):
        """点赞/取消点赞"""
        try:
            post = self.get_object()
            user_id = request.data.get('user')
            
            if not user_id:
                return Response(
                    {"error": "User ID is required"}, 
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 尝试创建点赞
            try:
                PostLike.objects.create(
                    post=post,
                    user_id=user_id
                )
                liked = True
            except IntegrityError:
                # 如果已经点赞，则取消点赞
                PostLike.objects.filter(
                    post=post,
                    user_id=user_id
                ).delete()
                liked = False

            # 更新点赞数
            post.likes_count = post.likes.count()
            post.save()

            return Response({
                'liked': liked,
                'likes_count': post.likes_count
            })

        except Exception as e:
            print(f"Error in like action: {str(e)}")
            return Response(
                {"error": str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    @action(detail=False, methods=['post'])
    def upload_image(self, request):
        """处理图片上传"""
        try:
            image = request.FILES.get('image')
            if not image:
                return Response({
                    'error': '没有找到图片'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 确保上传目录存在
            upload_dir = os.path.join(settings.MEDIA_ROOT, 'wall_images')
            if not os.path.exists(upload_dir):
                os.makedirs(upload_dir)
            
            # 生成文件名
            filename = f"{request.data.get('user')}_{timezone.now().strftime('%Y%m%d%H%M%S')}_{image.name}"
            filepath = os.path.join(upload_dir, filename)
            
            # 保存文件
            with open(filepath, 'wb+') as destination:
                for chunk in image.chunks():
                    destination.write(chunk)
            
            # 返回图片URL
            image_url = f"{settings.MEDIA_URL}wall_images/{filename}"
            
            return JsonResponse({
                'errno': 0,  # wangEditor 需要的格式
                'data': {
                    'url': image_url,
                    'alt': filename,
                    'href': image_url
                }
            })
        except Exception as e:
            print(f"Error uploading image: {str(e)}")
            return JsonResponse({
                'errno': 1,
                'message': '图片上传失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class WallCommentView(APIView):
    """帖子评论视图"""
    permission_classes = []

    def get(self, request, post_id):
        """获取帖子评论"""
        try:
            comments = WallComment.objects.filter(post_id=post_id).select_related('user')
            serializer = WallCommentSerializer(comments, many=True)
            return Response(serializer.data)
        except Exception as e:
            print(f"Error getting comments: {str(e)}")
            return Response([])

    def post(self, request):
        """创建评论"""
        try:
            serializer = WallCommentSerializer(data=request.data)
            if serializer.is_valid():
                comment = serializer.save()
                # 更新帖子的评论计数
                post = comment.post
                post.comments_count = post.comments.count()
                post.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            print(f"Error creating comment: {str(e)}")
            return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, comment_id):
        """删除评论"""
        try:
            comment = WallComment.objects.get(id=comment_id)
            comment.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except WallComment.DoesNotExist:
            return Response(
                {"error": "Comment not found"}, 
                status=status.HTTP_404_NOT_FOUND
            )

class PostCommentView(APIView):
    """帖子评论视图"""
    permission_classes = [IsAuthenticated]

    def get(self, request, post_id):
        """获取帖子评论列表"""
        try:
            post = WallPost.objects.get(id=post_id)
        except WallPost.DoesNotExist:
            return Response(
                {'message': '帖子不存在'},
                status=status.HTTP_404_NOT_FOUND
            )

        comments = post.comments.all()
        serializer = PostCommentSerializer(
            comments,
            many=True,
            context={'request': request}
        )
        return Response(serializer.data)

    def post(self, request, post_id):
        """创建评论"""
        try:
            post = WallPost.objects.get(id=post_id)
        except WallPost.DoesNotExist:
            return Response(
                {'message': '帖子不存在'},
                status=status.HTTP_404_NOT_FOUND
            )

        serializer = PostCommentSerializer(
            data=request.data,
            context={'request': request}
        )
        if serializer.is_valid():
            comment = serializer.save(
                post=post,
                user=request.user
            )
            # 更新帖子评论数
            post.comments_count = post.comments.count()
            post.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, comment_id):
        """删除评论"""
        try:
            comment = PostComment.objects.get(
                id=comment_id,
                user=request.user
            )
        except PostComment.DoesNotExist:
            return Response(
                {'message': '评论不存在或您没有权限'},
                status=status.HTTP_404_NOT_FOUND
            )

        post = comment.post
        comment.delete()
        # 更新帖子评论数
        post.comments_count = post.comments.count()
        post.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

class WallStatsView(APIView):
    """学习墙统计视图"""
    permission_classes = []

    def get(self, request):
        user_id = request.query_params.get('user_id')
        
        try:
            # 用户统计
            user_stats = {
                'total_posts': 0,
                'total_hours': 0,
                'avg_score': 0,
                'total_likes': 0,
                'study_days': 0
            }
            
            if user_id:
                user_posts = WallPost.objects.filter(user_id=user_id)
                user_stats.update({
                    'total_posts': user_posts.count(),
                    'total_hours': user_posts.aggregate(Sum('duration'))['duration__sum'] or 0,
                    'avg_score': user_posts.aggregate(Avg('score'))['score__avg'] or 0,
                    'total_likes': user_posts.aggregate(Sum('likes_count'))['likes_count__sum'] or 0,
                    'study_days': user_posts.dates('created_at', 'day').count()
                })

            # 热门标签
            all_posts = WallPost.objects.all()
            tags_count = {}
            for post in all_posts:
                for tag in post.tags:
                    tags_count[tag] = tags_count.get(tag, 0) + 1
            
            hot_tags = [
                {'name': tag, 'count': count}
                for tag, count in sorted(
                    tags_count.items(), 
                    key=lambda x: x[1], 
                    reverse=True
                )[:10]
            ]

            # 学习达人
            top_users = User.objects.annotate(
                study_hours=Sum('wall_posts__duration'),
                posts_count=Count('wall_posts')
            ).filter(
                study_hours__gt=0
            ).order_by('-study_hours')[:10]

            top_learners = [{
                'id': user.id,
                'username': user.username,
                'study_hours': float(user.study_hours or 0),
                'posts_count': user.posts_count or 0
            } for user in top_users]

            # 添加学习时间趋势
            if user_id:
                study_trend = (
                    WallPost.objects
                    .filter(user_id=user_id)
                    .annotate(date=TruncDate('created_at'))
                    .values('date')
                    .annotate(duration=Sum('duration'))
                    .order_by('date')
                )

                trend_data = [{
                    'date': item['date'].strftime('%Y-%m-%d'),
                    'duration': float(item['duration'] or 0)
                } for item in study_trend]
            else:
                trend_data = []

            return Response({
                'user_stats': user_stats,
                'hot_tags': hot_tags,
                'top_learners': top_learners,
                'study_trend': trend_data
            })

        except Exception as e:
            print(f"Error getting stats: {str(e)}")
            return Response(
                {"error": str(e)}, 
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
